package user

import (
	"context"
	"github.com/jinzhu/copier"
	"go.uber.org/zap"
	"navi-mumbai/app/rpc/usercenter/pb"
	pb2 "navi-mumbai/app/rpc/wallet/pb"
	"navi-mumbai/common/key/dbkey"
	"navi-mumbai/common/key/userkey"
	"navi-mumbai/common/key/walletkey"
	"navi-mumbai/common/xerr"
	"strings"

	"navi-mumbai/app/api/business/internal/svc"
	"navi-mumbai/app/api/business/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserRegisterLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserRegisterLogic {
	return &UserRegisterLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserRegisterLogic) UserRegister(req *types.UserRegisterReq, ip string) (resp *types.UserLoginResp, err error) {
	l.Logger.Infof("UserRegisterLogic username %s ip %s, AppsFlyerUID: %s", req.Username, ip, req.AppsFlyerUID)
	if req.Passwd == "" || req.Username == "" || req.Email == "" {
		return nil, xerr.NewGrpcErrCodeMsg(xerr.RequestParamError, "username or passwd is empty")
	}
	var in pb.LoginUserReq
	in.UserPass = req.Passwd
	in.AuthType = userkey.UserAuthTypePasswd
	in.AuthKey = req.Username
	if ip != "" {
		ips := strings.Split(ip, ",")
		if len(ips) > 0 {
			in.Ip = ips[0]
		}
	}
	in.AppVer = req.AppVer
	in.UserChannel = req.UserChannel
	in.Device = req.Device
	in.Email = req.Email
	in.DeviceId = req.DeviceId
	in.AppsFlyerUID = req.AppsFlyerUID
	in.Pid = req.Pid
	l.Logger.Infof("in UserRegister...")
	var rsp *pb.LoginUserResp
	rsp, err = l.svcCtx.UcUserRpc.Register(l.ctx, &in)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return
	}
	resp = &types.UserLoginResp{
		Token:   &types.UserToken{},
		Account: &types.UserAccount{},
		Profile: &types.UserProfile{},
	}
	_ = copier.Copy(resp, rsp)

	// 初始化钱包 注册默认赠送
	if rsp.Account.IsNewUser == dbkey.Enable {
		l.firstRegister(rsp.Account.Uid)
	}
	return
}

// firstRegister 首次注册
func (l *UserRegisterLogic) firstRegister(uid int64) {
	_, err := l.svcCtx.WalletSysRpc.DepositDirect(l.ctx, &pb2.DepositDirectReq{
		Uid:            uid,
		MoneyType:      walletkey.UsingCurrencyType,
		MoneyAmount:    userkey.LoginRewardMoneyAmount,
		CurrencyType:   0,
		CurrencyAmount: "",
		PayChannelId:   walletkey.PayChannelIdSystem,
		ExFlow:         "",
	})
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		l.Logger.Errorf("UserRegisterLogic firstRegister DepositDirect uid:%d err:%v", uid, err)
		return
	}
}
